<?php

/**
 *
 * @author lovebing <lovebing365@126.com> Created on 2014-10-5 22:43:59
 */
class WechatPay extends Wechat {

    private $appId;
    private $key;
    private $mchId;
    private $tradeType = array('JSAPI', 'NATIVE', 'APP');
    private static $instance = null;
    private $errorMessage = '';

    /**
     * 
     * @param type $appId
     * @param type $key
     * @param type $mchId
     */
    public function __construct($appId, $key, $mchId) {
        $this->appId = $appId;
        $this->key = $key;
        $this->mchId = $mchId;
    }

    /**
     * 
     * @param type $appId
     * @param type $key
     * @param type $mchId
     * @return type
     */
    public static function getInstance($appId, $key, $mchId) {
        if (is_null(self::$instance)) {
            self::$instance = new self($appId, $key, $mchId);
        }
        self::$instance->errorMessage = '';
        return self::$instance;
    }

    /**
     * 
     * @param type $openid
     * @param type $orderId
     * @param type $totalfee
     * @param type $notifyUrl
     * @param type $desc
     * @param type $tradeType
     * @return string
     */
    public function createPrepayOrder($openid, $orderId, $totalfee, $notifyUrl, $desc, $tradeType = 'JSAPI') {
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $params = array(
            'openid' => $openid,
            'body' => $desc,
            'out_trade_no' => $orderId,
            'total_fee' => $totalfee,
            'notify_url' => $notifyUrl,
            'trade_type' => $tradeType,
            'appid' => $this->appId,
            'mch_id' => $this->mchId,
            'spbill_create_ip' => Net::getIp(),
            // 'device_info' => '',
            'nonce_str' => md5(uniqid(true)),
                //  'attach' => '',
                // 'time_start' => date('YmdHis'),
                // 'time_expire' => date('YmdHis', strtotime('+24 hours')),
                //  'goods_tag' => '',
                // 'product_id' => ''
        );
        $params['sign'] = self::createPaySign($params, $this->key);
        $http = HTTPClient::getInstance();
        $xml = XML::arrayToXml($params);
        $res = XML::xmlToArray($http->postText($url, $xml));
        if ($res['return_code'] == 'FAIL' || $res['result_code'] == 'FAIL') {
            $this->errorMessage = isset($res['err_code_des']) ? $res['err_code_des'] : $res['return_msg'];
            return false;
        }
        $this->errorMessage = '';
        return $res['prepay_id'];
    }

    public function getErrorMessage() {
        return $this->errorMessage;
    }

    /**
     *
     * @param type $prepayId
     * @return type
     */
    public function createPayJsApiParams($prepayId) {
        $params = array(
            'appId' => $this->appId,
            'timeStamp' => time() . '',
            'nonceStr' => uniqid(),
            'package' => 'prepay_id=' . $prepayId,
            'signType' => 'MD5'
        );
        $params['paySign'] = self::createPaySign($params, $this->key);
        return $params;
    }

    public function queryOrder($out_trade_no) {
        $url = 'https://api.mch.weixin.qq.com/pay/orderquery';
        $params = array(
            'appid' => $this->appId,
            'mch_id' => $this->mchId,
            'out_trade_no' => $out_trade_no,
            'nonce_str' => md5(uniqid() . microtime(true))
        );
        $params['sign'] = self::createPaySign($params, $this->key);
        $xml = XML::arrayToXml($params);
        $http = new HTTPClient();
        $res = $http->postText($url, $xml);
        return XML::xmlToArray($res);
    }

}
